import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Image,
  Drawer,
  Modal,
  InputNumber,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  ExclamationCircleFilled,
  CloseOutlined,
} from "@ant-design/icons";
import { text_check, post_axios, format_time, show_img_url } from "../../utils";
import "./index.scss";
import videojs from "video.js";
import VideoJS from "../../modules/videoJs";

export default function CustomerComplaint(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  const { confirm } = Modal;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [out_trade_no, setOut_trade_no] = useState("");
  const [table_data_list, setTable_data_list] = useState([]);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      out_trade_no: out_trade_no,
    };
    setSpinning(true);
    let res = await post_axios("customer_complaint", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setTable_data_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: "公司",
      dataIndex: "company",
      align: "center",
    },
    {
      title: "机器号",
      dataIndex: "avm",
      align: "center",
    },
    {
      title: "订单号",
      dataIndex: "out_trade_no",
      align: "center",
      width: 350,
    },
    {
      title: "状态",
      align: "center",
      width: 100,
      render: (_, record) => (
        <>
          {record.vision_status == "not_on_shelf" ? (
            <span style={{ color: "orange" }}>未上架</span>
          ) : (
            <span style={{ color: "red" }}>非友好</span>
          )}
        </>
      ),
    },
    {
      title: "错误信息",
      dataIndex: "msg",
      width: 400,
      align: "center",
    },
    {
      title: "创建时间",
      width: 200,
      dataIndex: "ctime",
      align: "center",
    },
    {
      align: "center",
      hidden: !Boolean(menu_action.indexOf("m_cancel_order") > -1),
      render: (_, record) => (
        <Button type="primary" onClick={() => get_video_func(record)}>
          查看视频
        </Button>
      ),
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.out_trade_no);
    setclickRow(row);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey("");
    setclickRow([]);
    getData(page, rows);
  };

  const [mp4_video_drawer_show, setMp4_video_drawer_show] = useState(false);
  const [m3u8_video_drawer_show, setM3u8_video_drawer_show] = useState(false);
  const [m3u8_arr, setM3u8_arr] = useState([]);
  const [mp4_arr, setMp4_arr] = useState([]);

  const playerRef = React.useRef(null);
  const videoJsOptions = (src) => {
    return {
      autoplay: true,
      controls: true,
      responsive: true,
      fluid: true,
      sources: [
        {
          src,
          type: "application/x-mpegURL",
        },
      ],
    };
  };

  const handlePlayerReady = (player) => {
    playerRef.current = player;

    // You can handle player events here, for example:
    player.on("waiting", () => {
      videojs.log("player is waiting");
    });

    player.on("dispose", () => {
      videojs.log("player will dispose");
    });
  };
  const get_video_func = async (item) => {
    console.log(item);
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      urls: item.urls_after,
    };
    let res = await post_axios("customer_complaint", "m_video", upMsg);
    if (!res) return;
    let rows = res.data_rows.rows;
    if (typeof rows !== "object" || rows.length == 0) {
      alert("视频错误");
      return;
    }
    if (item.vision_type == "cloud_walk") {
      console.log("m3u8");
      setM3u8_video_drawer_show(true);
      setM3u8_arr(rows);
    } else {
      console.log("mp4");
      setMp4_video_drawer_show(true);
      setMp4_arr(rows);
    }
  };

  const [avm_kind_product_list, setAvm_kind_product_list] = useState([]);
  const [checked_product_list, setChecked_product_list] = useState([]);
  const [
    create_supplementary_payment_show,
    setCreate_supplementary_payment_show,
  ] = useState(false);
  const [order_amount, setOrder_amount] = useState(0);
  const [supplementary_payment_notes, setSupplementary_payment_notes] =
    useState("");
  const complete_order = async () => {
    if (clickRowKey === "") {
      message.warning({
        content: "请选择一条订单",
      });
      return;
    }
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      avm: clickRow.avm,
    };
    let res = await post_axios("customer_complaint", "m_query_goods", upMsg);
    if (!res) return;
    const newRows = res.data_rows.rows.map((item) => {
      item["price"] = item["price"] / 100;
      item["pic"] = show_img_url(item, local_company_object.company);
      return item;
    });
    setAvm_kind_product_list(newRows);
    setChecked_product_list([]);
    setOrder_amount(0);
    setSupplementary_payment_notes("");
    setCreate_supplementary_payment_show(true);
  };
  const product_click_func = (obj) => {
    obj["checked_num"] = 1;
    setChecked_product_list([...checked_product_list, obj]);
    const newList = avm_kind_product_list.filter(
      (item) => item.barcode !== obj.barcode
    );
    setAvm_kind_product_list(newList);
    count_order_number([...checked_product_list, obj]);
  };
  const delete_checked_product = (obj) => {
    setAvm_kind_product_list([...avm_kind_product_list, obj]);
    const newList = checked_product_list.filter(
      (item) => item.barcode !== obj.barcode
    );
    setChecked_product_list(newList);
    count_order_number(newList);
  };

  const InputNumberonChange = (value, index) => {
    const newList = checked_product_list;
    newList[index]["checked_num"] = value;
    setChecked_product_list(newList);
    count_order_number(newList);
  };
  const count_order_number = (checked_product_list) => {
    let amount = checked_product_list.reduce((sum, currentValue) => {
      return (sum +=
        Number(currentValue.price) * 100 * currentValue.checked_num);
    }, 0);
    setOrder_amount(amount / 100);
  };

  const create_supplementary_payment_confirm = async () => {
    let array_goods = checked_product_list.map((item) => {
      return {
        goods_id: item.barcode,
        goods_name: item.name,
        goods_price: Number(item.price) * 10 * 10,
        goods_count: item.checked_num,
        goods_amount: Number(item.price) * 10 * 10 * item.checked_num,
      };
    });
    let upMsg = {
      ...clickRow,
      company_id: local_company_object.id,
      company: local_company_object.company,
      price: order_amount * 10 * 10,
      array_goods,
    };
    let res = await post_axios("customer_complaint", "m_complete_order", upMsg);
    if (!res) return;
    message.warning({
      content: t("common.success"),
    });
    setCreate_supplementary_payment_show(false);
    search_data();
  };

  const cancel_order = () => {
    confirm({
      title: "提示",
      icon: <ExclamationCircleFilled />,
      content: "确认取消此订单?",
      onOk: async () => {
        let upMsg = {
          company_id: local_company_object.id,
          company: local_company_object.company,
          out_trade_no: clickRow.out_trade_no,
          avm: clickRow.avm,
          vision_type: clickRow.vision_type,
        };
        let res = await post_axios(
          "customer_complaint",
          "m_cancel_order",
          upMsg
        );
        if (!res) return;
        message.success({
          content: t("common.success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("customer_complaint")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="customer_complaint modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">{t("assets.strategy_name")}</div>
            <Input
              placeholder=" "
              value={out_trade_no}
              size="small"
              allowClear={true}
              onChange={(e) => setOut_trade_no(e.target.value)}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 完结订单 */}
            {menu_action.indexOf("m_complete_order") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={complete_order}
              >
                {text_check(user_power_lang["m_complete_order"])}
              </Button>
            ) : (
              ""
            )}
            {/* 取消订单 */}
            {menu_action.indexOf("m_cancel_order") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={cancel_order}
              >
                {text_check(user_power_lang["m_cancel_order"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={table_data_list}
              size="small"
              bordered
              columns={columns}
              rowKey="out_trade_no"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.out_trade_no == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title="客诉完结订单"
        open={create_supplementary_payment_show}
        onCancel={() => setCreate_supplementary_payment_show(false)}
        classNames={{
          body: "edit_dialog_body customer_complaint_dialog",
          wrapper: "edit_900_style",
        }}
        maskClosable={false}
        destroyOnClose={true}
        footer={[
          <span
            style={{ fontSize: "20px", fontWeight: "600", marginRight: "15px" }}
          >
            总金额:{order_amount}
          </span>,
          <Button type="primary" onClick={create_supplementary_payment_confirm}>
            {t("common.confirm")}
          </Button>,
        ]}
      >
        <div className="product_content">
          <div className="kind_product">
            {avm_kind_product_list.map((item) => {
              return (
                <div
                  className="product_box"
                  key={item.barcode}
                  onClick={() => product_click_func(item)}
                >
                  <div className="product_img">
                    {item.pic && item.pic.length !== 0 ? (
                      <Image
                        className="table_img"
                        src={item.pic}
                        fit="contain"
                        preview={false}
                      />
                    ) : (
                      ""
                    )}
                  </div>
                  <div className="product_name">{item.name}</div>
                  <div className="product_price">¥{item.price}</div>
                </div>
              );
            })}
          </div>
          <div className="checked_box">
            {checked_product_list.map((item, index) => {
              return (
                <div className="product_box" key={item.barcode}>
                  <div className="product_img">
                    {item.pic && item.pic.length !== 0 ? (
                      <Image
                        className="table_img"
                        src={item.pic}
                        fit="contain"
                        preview={false}
                      />
                    ) : (
                      ""
                    )}
                  </div>
                  <div className="product_word">
                    <div className="product_name">{item.name}</div>
                    <div className="product_price">¥{item.price}</div>
                    <div className="product_price">
                      <InputNumber
                        min={1}
                        size="small"
                        efaultValue={item.checked_num ? item.checked_num : 1}
                        onChange={(value) => InputNumberonChange(value, index)}
                      />
                    </div>
                  </div>
                  <div
                    className="close_btn"
                    onClick={() => delete_checked_product(item)}
                  >
                    <CloseOutlined />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Modal>

      <Drawer
        title=" "
        placement="top"
        onClose={() => setMp4_video_drawer_show(false)}
        open={mp4_video_drawer_show}
        className="drawer_style"
        styles={{
          content: {
            height: "450px",
          },
          body: {
            height: "400px",
          },
        }}
      >
        {mp4_arr.map((item) => {
          return (
            <div className="video_box" key={item}>
              <video src={item} controls autoPlay={mp4_arr.length == 1}>
                您的浏览器不支持 video 标签。
              </video>
            </div>
          );
        })}
      </Drawer>
      <Drawer
        title=" "
        placement="top"
        onClose={() => setM3u8_video_drawer_show(false)}
        open={m3u8_video_drawer_show}
        className="drawer_style"
        styles={{
          content: {
            height: "450px",
          },
          body: {
            height: "400px",
          },
        }}
      >
        {m3u8_arr.map((item) => {
          return (
            <div className="video_box" key={item}>
              <VideoJS
                options={videoJsOptions(item)}
                onReady={handlePlayerReady}
              />
            </div>
          );
        })}
      </Drawer>
    </>
  );
}
